package com.ty.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.ty.dao.ProductDao;
import com.ty.dto.FileInfo;
import com.ty.dto.UploadInfo;
import com.ty.entity.Product;
import com.ty.entity.ProductQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service//组件
public class UploadService {

    @Value("${upload.domain}")
    private String domain;
    @Value("${upload.path}")
    private String path;

    @Autowired
    OssService ossService;


    //nginx  1： 静态资源服务器
    public String upload(UploadInfo uploadInfo) {

        String name = IdUtil.getSnowflakeNextIdStr()+"_"+ uploadInfo.getName();
        String base64 = uploadInfo.getBase64();
        String[] base64Array = StrUtil.splitToArray(base64, ",");
        byte[] bytes = Base64.decode(base64Array[1]);
        //FileUtil.writeBytes(bytes, path + name);
        String  url =   ossService.uploadFile(name,new ByteArrayInputStream(bytes));
        return  url;// domain + "/images/"+name;
    }

    public List<FileInfo> select(Integer code) {
//        List<FileInfo> fileInfos = Arrays.stream(FileUtil.ls(path)).map(file -> {
//            FileInfo fileInfo = new FileInfo();
//            fileInfo.setName(file.getName());
//            fileInfo.setUrl(domain + "/images/" + file.getName());
//            return fileInfo;
//        }).collect(Collectors.toList());

        return  ossService.select(code);

    }
}
